uniform sampler2D texture, texture2, texture3;
uniform float state;


void main()
{
	//Texture with green-screen.
	vec4 tex = texture2D(texture, gl_TexCoord[0].xy); 
	//Background texture.	
	vec4 tex2 = texture2D(texture2, gl_TexCoord[0].xy); 
	vec4 tex3 = texture2D(texture3, gl_TexCoord[0].xy); 

	vec4 final_color = vec4(0.0, 0.0, 0.0, 0.0);

		//FUNGERANDE GREEN-SCREEN FILTER

	vec3 green = vec3(0.0*(1.0/256.0), 256.0*(1.0/256.0), 0.0*(1.0/256.0));

	//Calulate "distance" from green (0.0, 1.0, 0.0)
	//to current color.
	float green_dist = sqrt((tex.r-green.r)*(tex.r-green.r)+
				(tex.g-green.g)*(tex.g-green.g)+
				(tex.b-green.b)*(tex.b-green.b));


	
	//Calulate "distance" from black (0.0, 0.0, 0.0) 
	//to current color to remove unwanted shadows.
	float dark_dist = sqrt((tex.r*tex.r)+(tex.g*tex.g)+(tex.b*tex.b));
	
	//Max distance to green.
	float green_tolerance = 0.81;
	//Max distance to black.
	float dark_tolerance = 0.5;

	//If the current color i within the radius of green_tolerance,
	//replace the pixel with the corresponding one from background texture.
	if ((tex.g/tex.r > 1.1 && tex.g/tex.b > 1.1) && tex.g > 0.2) {
		final_color += tex2;
	}
	//Else, keep current color from the green-screen texture.
	else {
		final_color += tex;
	}

	gl_FragColor = final_color;

}
